package com.module.product.manager;
import java.sql.Connection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.Transaction;

import base.common.CUDEnum;
import base.dao.GenericHibernateDao;
import base.db.HibernateSessionFactory;
import base.manager.GenericHibernateManager;
import base.util.Page;

import com.module.product.common.IDManage;
import com.module.product.dao.AttrItemDao;
import com.module.product.dao.AttrValueDao;
import com.module.product.dao.ProductDao;
import com.module.product.vo.Category;
import com.module.product.vo.Product;

/**
* 商品业务处理类
*
* @author  王勇云
* @version  [V1.0, Jul 22, 2011]
* @see  [相关类/方法]
* @since  [二代服务平台/商品]
*/
public class ProductManager extends GenericHibernateManager<Product,String>{
    private static final ProductManager instance = new ProductManager();
    
    static Logger logger = Logger.getLogger(ProductManager.class.getName());
    private ProductManager(){}
    
    public synchronized static ProductManager getInstance() {
        return instance;
    }
    
    ProductDao dao = ProductDao.getInstance();
    AttrValueDao attrValueDao = AttrValueDao.getInstance();
    AttrItemDao attrItemDao = AttrItemDao.getInstance();
    
    /**
     * 保存或更新
     * @param obj
     * @return
     * @throws Exception 
     */
    public Product saveProductAndAttr(Product obj) throws Exception{
    	Session session = HibernateSessionFactory.getSession();
    	Connection conn = session.connection();
    	Transaction tx =session.beginTransaction();
    	try{
            if(StringUtils.isBlank(obj.getId())){//添加
                obj.setId(IDManage.getUUIDString());
                obj.setStatus(CUDEnum.C.toString());
                obj.setCreateTime(new Date());
                save(obj);
            }else{
                obj.setStatus(CUDEnum.U.toString());
                obj.setUpdateTime(new Date());
                update(obj);
            }
            
             dao.deleteAllCategorybyProductId(session,conn,obj.getId());
            
             List<String> categorylist  = obj.getCategoryList();
             if(categorylist!=null){
                 for(String cateId:categorylist){
                     dao.saveCategoryIdandProductId(session,conn,cateId, obj.getId());
                 }
             }
             tx.commit();
    	}catch(Exception e){
    		tx.rollback();
    		throw e;
    		
    		
    	}finally{
    		this.closeSession();
    	}
        return obj ;
    }
    
    public boolean delete(Product obj) throws Exception
    {
    	Session session = HibernateSessionFactory.getSession();
    	Transaction tx =session.beginTransaction();
    	boolean flag = false;
    	try{
    		flag = dao.deleteObjs(session,obj);
            tx.commit();
    	}catch(Exception e){
            tx.rollback();
            throw e;
            
    	}finally{
    		this.closeSession();
    	}
    	return flag;

    }
    
    public boolean update(Product obj) throws Exception
    {
    	Session session = HibernateSessionFactory.getSession();
    	boolean flag = false;
    	try{
    		flag =  dao.update(session,obj);
    	}catch(Exception e){
    		throw e;
    		
    	}finally{
    		this.closeSession();
    	}
    	return flag;
    }
    
    public Product get(String id) throws Exception
    {
    	Session session = HibernateSessionFactory.getSession();
    	Connection conn = session.connection();
    	Transaction tx =session.beginTransaction();
        Product p = dao.get(session,id);
        try{
        	p.setCategoryList(dao.findCategoryIdbyProductId(session,conn,id));
        }catch(Exception e){
        	throw e;
        	
    	}finally{
    		this.closeSession();
    	}
        
        return p;
    }
    
    public Page getList(Product obj,Page page) throws Exception{
    	Session session = HibernateSessionFactory.getSession();
        
        try{
        	dao.getList(session,obj,page);
        }catch(Exception e){
        	throw e;
        	
    	}finally{
    		this.closeSession();
    	}        	
        setCategoryName(page);
        return page;
    }

    private void setCategoryName(Page page) throws Exception{
    	Session session = HibernateSessionFactory.getSession();
    	Connection conn = session.connection();
    	Transaction tx =session.beginTransaction();
    	try{
	        List list = page.getRows();
	        Category c = null;
	        if(list!=null){
	            for(Product p :(List<Product>)list){
	                p.setCategoryName(getCategoryNamesFromList(dao.findCategoryListbyProductId(session,conn,p.getId())));
	            }
	        }
	        tx.commit();
	    }catch(Exception e){
	    	tx.rollback();
	    	throw e;
	    }finally{
	    	this.closeSession();
	    }

	}

    
    private String getCategoryNamesFromList(List<Category> list){
        StringBuffer categoryNames = new StringBuffer();
        if(list!=null){
            for(int i = 0;i<list.size();i++){
                if(i!=0){
                    categoryNames.append(" , "); 
                }
                categoryNames.append(list.get(i).getName());
            }
        }
        return categoryNames.toString();
    }
    
    
    
    
    public List<Product> findProductListbyOrgId(Product obj) throws Exception{
    	Session session = HibernateSessionFactory.getSession();
    	List<Product> list = null;
    	try{
    		list = dao.findProductListbyOrgId(session,obj);
    	}catch(Exception e){
    		throw e;
    		
    	}finally{
    		this.closeSession();
    	}
        return list;
    }
    
    public Product getremotProduct(String id) throws Exception
    {
    	Session session = HibernateSessionFactory.getSession();
    	Transaction tx =session.beginTransaction();
        Product p = null;
        try{
	        p = dao.get(session,id);
	        p.setList(attrValueDao.getattvbyproductid(session,p.getId()));
	        tx.commit();
        }catch(Exception e){
        	tx.rollback();
        	throw e;
        	
        }finally{
        	this.closeSession();
        }
        return p;
    }
    /*
    public ProductBeanUnit decreaseProductStocks(ProductBeanUnit beanUnit) throws Exception{
    	Session session = HibernateSessionFactory.getSession();
    	Transaction tx =session.beginTransaction();
    	boolean b = false;
    	try{
    		b =dao.decreaseProductStocks(session,beanUnit.getList());
    		tx.commit();
	    	Map map = new HashMap();
	    	map.put("state", b);
	    	if(b){
	    		map.put("msg", "保存成功");
	    	}else {
	    		map.put("msg", "保存失败");
	    	}
	    	beanUnit.setResult(map);
    	}catch(Exception e){
    		tx.rollback();
    		throw e;
    		
    	}finally{
    		this.closeSession();
    	}
    	return beanUnit;
    }
	*/
    /**
     * 通过商品ID获取相应的属性及视频，图片;
     * @param beanUnit
     * @throws Exception 
     */
    /*
	public boolean getProductAttrByProductId(ProductBeanUnit beanUnit) throws Exception {
		Session session = HibernateSessionFactory.getSession();
    	Connection conn = session.connection();
    	boolean result = false;
    	try{
    		result = dao.getProductAttrByProductId(session,conn,beanUnit);
    	}catch(Exception e){    		
    		throw e;
    		
    	}finally{
    		this.close(conn);
    		this.closeSession();
    	}
		return result;
	}
	*/
	public boolean getCountByAttrGrop(String attrGroupId) throws Exception{
		try {
			long productCount = dao.getCountByAttrGrop(this.getSession(),
					attrGroupId);
			if (productCount > 0) {
				return true;
			}
			return false;
		} catch (Exception e) {
			throw e;
		}finally{
			this.closeSession();
		}
	}

	@Override
	public GenericHibernateDao<Product, String> getDao() {
		// TODO Auto-generated method stub
		return dao;
	}
    
    
}
